package com.doctracker.service;

import org.apache.poi.ss.usermodel.BorderStyle;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.FillPatternType;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.VerticalAlignment;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.util.CellRangeAddress;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

/**
 * Excel模板生成服务
 * 负责创建标准的名单导入模板
 */
public class ExcelTemplateService {
    
    /**
     * 生成标准名单模板
     * 
     * @param saveFile 保存文件路径
     * @return 是否生成成功
     */
    public boolean generateTemplate(File saveFile) {
        try (Workbook workbook = new XSSFWorkbook()) {
            Sheet sheet = workbook.createSheet("学生名单");
            
            // 创建样式
            createStyles(workbook, sheet);
            
            // 创建内容
            createContent(sheet, workbook);
            
            // 设置列宽
            setColumnWidths(sheet);
            
            // 保存文件
            try (FileOutputStream outputStream = new FileOutputStream(saveFile)) {
                workbook.write(outputStream);
            }
            
            System.out.println("Excel模板生成成功: " + saveFile.getAbsolutePath());
            return true;
            
        } catch (IOException e) {
            System.err.println("生成Excel模板失败: " + e.getMessage());
            e.printStackTrace();
            return false;
        }
    }
    
    /**
     * 创建样式
     */
    private void createStyles(Workbook workbook, Sheet sheet) {
        // 设置默认行高
        sheet.setDefaultRowHeight((short) 400);
        
        // 冻结窗格（冻结标题行）
        sheet.createFreezePane(0, 3);
    }
    
    /**
     * 创建内容
     */
    private void createContent(Sheet sheet, Workbook workbook) {
        // 创建样式
        CellStyle titleStyle = createTitleStyle(workbook);
        CellStyle headerStyle = createHeaderStyle(workbook);
        CellStyle exampleStyle = createExampleStyle(workbook);
        
        int rowNum = 0;
        
        // 第1行：标题和使用说明
        Row titleRow = sheet.createRow(rowNum++);
        Cell titleCell = titleRow.createCell(0);
        titleCell.setCellValue("学生名单导入模板 - 使用说明：请在下方填写学生信息，姓名为必填项，其他为可选项");
        titleCell.setCellStyle(titleStyle);
        
        // 合并标题行（A1:E1）
        sheet.addMergedRegion(new CellRangeAddress(0, 0, 0, 4));
        
        // 第2行：空行
        sheet.createRow(rowNum++);
        
        // 第3行：列标题
        Row headerRow = sheet.createRow(rowNum++);
        String[] headers = {"序号", "姓名*", "学号", "班级", "备注"};
        for (int i = 0; i < headers.length; i++) {
            Cell cell = headerRow.createCell(i);
            cell.setCellValue(headers[i]);
            cell.setCellStyle(headerStyle);
        }
        
        // 第4-5行：示例数据
        String[][] examples = {
            {"1", "张三", "20210001", "计科1班", "示例学生1"},
            {"2", "李四", "20210002", "计科2班", "示例学生2，请删除此行后填写真实数据"}
        };
        
        for (String[] example : examples) {
            Row exampleRow = sheet.createRow(rowNum++);
            for (int i = 0; i < example.length; i++) {
                Cell cell = exampleRow.createCell(i);
                cell.setCellValue(example[i]);
                cell.setCellStyle(exampleStyle);
            }
        }
        
        // 添加10行空白行供用户填写
        for (int i = 0; i < 10; i++) {
            Row emptyRow = sheet.createRow(rowNum++);
            // 预填序号
            Cell seqCell = emptyRow.createCell(0);
            seqCell.setCellValue(i + 3); // 从3开始
        }
    }
    
    /**
     * 设置列宽
     */
    private void setColumnWidths(Sheet sheet) {
        sheet.setColumnWidth(0, 2000);  // 序号列
        sheet.setColumnWidth(1, 3000);  // 姓名列
        sheet.setColumnWidth(2, 4000);  // 学号列
        sheet.setColumnWidth(3, 3500);  // 班级列
        sheet.setColumnWidth(4, 6000);  // 备注列
    }
    
    /**
     * 创建标题样式
     */
    private CellStyle createTitleStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        
        // 字体设置
        font.setFontName("Microsoft YaHei");
        font.setFontHeightInPoints((short) 12);
        font.setBold(true);
        font.setColor(IndexedColors.DARK_BLUE.getIndex());
        
        // 样式设置
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.LIGHT_CORNFLOWER_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        return style;
    }
    
    /**
     * 创建表头样式
     */
    private CellStyle createHeaderStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        
        // 字体设置
        font.setFontName("Microsoft YaHei");
        font.setFontHeightInPoints((short) 11);
        font.setBold(true);
        font.setColor(IndexedColors.WHITE.getIndex());
        
        // 样式设置
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.CENTER);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.DARK_BLUE.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        return style;
    }
    
    /**
     * 创建示例数据样式
     */
    private CellStyle createExampleStyle(Workbook workbook) {
        CellStyle style = workbook.createCellStyle();
        Font font = workbook.createFont();
        
        // 字体设置
        font.setFontName("Microsoft YaHei");
        font.setFontHeightInPoints((short) 10);
        font.setColor(IndexedColors.GREY_50_PERCENT.getIndex());
        font.setItalic(true);
        
        // 样式设置
        style.setFont(font);
        style.setAlignment(HorizontalAlignment.LEFT);
        style.setVerticalAlignment(VerticalAlignment.CENTER);
        style.setFillForegroundColor(IndexedColors.GREY_25_PERCENT.getIndex());
        style.setFillPattern(FillPatternType.SOLID_FOREGROUND);
        
        // 边框
        style.setBorderTop(BorderStyle.THIN);
        style.setBorderBottom(BorderStyle.THIN);
        style.setBorderLeft(BorderStyle.THIN);
        style.setBorderRight(BorderStyle.THIN);
        
        return style;
    }
    
    /**
     * 生成默认文件名
     * 
     * @return 文件名
     */
    public String generateDefaultFileName() {
        String timestamp = LocalDateTime.now().format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
        return "学生名单模板_" + timestamp + ".xlsx";
    }
} 